(function(angular) {
    'use strict';

    angular.module('app.usuarios')
        .controller('ListarUsuariosCtrl', ['$scope', '$filter', '$mdDialog', '$state', 'UsuariosService', ListarCtrl])
        .controller('EditarUsuariosCtrl', ['$scope', '$filter', '$mdDialog', '$stateParams', 'logger', 'UsuariosService', 'RolesService', 'FileReaderFactory', EditarCtrl]);

    function ListarCtrl($scope, $filter, $mdDialog, $state, UsuariosService) {
        var init;

        $scope.items = [];
        $scope.filteredItems = [];
        $scope.searchKeywords = '';
        $scope.row = '';
        $scope.numPerPageOpt = [3, 5, 10, 20];
        $scope.numPerPage = $scope.numPerPageOpt[2];
        $scope.currentPage = 1;
        $scope.currentPageItems = [];

        $scope.select = function(page) {
            var end, start;
            start = (page - 1) * $scope.numPerPage;
            end = start + $scope.numPerPage;
            return $scope.currentPageItems = $scope.filteredItems.slice(start, end);
        };

        $scope.onFilterChange = function() {
            $scope.select(1);
            $scope.currentPage = 1;
            return $scope.row = '';
        };

        $scope.onNumPerPageChange = function() {
            $scope.select(1);
            return $scope.currentPage = 1;
        };

        $scope.onOrderChange = function() {
            $scope.select(1);
            return $scope.currentPage = 1;
        };

        $scope.search = function() {
            $scope.filteredItems = $filter('filter')($scope.items, $scope.searchKeywords);
            return $scope.onFilterChange();
        };

        $scope.order = function(rowName) {
            if ($scope.row === rowName) {
                return;
            }
            $scope.row = rowName;
            $scope.filteredItems = $filter('orderBy')($scope.items, rowName);
            return $scope.onOrderChange();
        };

        $scope.editar = function(item) {
            $state.go('usuarios_editar', {
                id: item.Id
            });
        };

        $scope.eliminar = function($event, item) {
            var DialogController = ['$scope', '$mdDialog', function ($scope, $mdDialog) {
                $scope.hide = function() {
                    $mdDialog.hide();
                };
                $scope.cancel = function() {
                    $mdDialog.cancel();
                };
            }];

            $mdDialog.show({
                controller: DialogController,
                templateUrl: '/views/usuarios/dialogo-confirmacion-eliminar-usuario.html',
                targetEvent: $event,
            })
            .then(function() {
                // TODO: hacer la funcionalidad que elimina
                UsuariosService.delette(item.Id)
                    .then(function(result) {
                        init();
                    }, null);
            }, null);
        };


        init = function() {
            UsuariosService.read()
            .then(function(result) {
                $scope.items = angular.fromJson(result.data);
                $scope.search();
                $scope.select($scope.currentPage);
            }, null);
        };

        init();
    }

    function EditarCtrl ($scope, $filter, $mdDialog, $stateParams, logger, UsuariosService, RolesService, FileReaderFactory) {
        $scope.usuario = {};
        $scope.dateFormat = 'dd/MM/yyyy';

        $scope.maxDate = new Date();
        $scope.openDatepicker = function($event) {
            $event.preventDefault();
            $event.stopPropagation();

            $scope.opened = true;
        };

        $scope.guardarCambios = function() {
            var usr = angular.copy($scope.usuario),
                format = 'dd/MM/yyyy';
            usr.FechaIngreso = $filter('date')(usr.FechaIngreso, format);
            usr.FechaNacimiento = $filter('date')(usr.FechaNacimiento, format);
            usr.FotoBase64 = usr.FotoBase64.slice(23);
            //console.log(angular.toJson(usr, true));
            UsuariosService.update(usr).then(function() {
                logger.logSuccess($filter('translate')('GENERIC_AJAX_SUCCESS_SAVE'));
            });
        };

        $scope.$watch('usuario', function(newValue, oldValue) {
            if (!newValue.FotoBase64)
                return;
            if (newValue.FotoBase64.slice(0, 3) !== 'data')
                newValue.FotoBase64 = 'data:image/jpeg;base64,' + newValue.FotoBase64;
        });

        // Para no repetir codigo todos los metodos de constantes llaman a esta funcion
        // como todos tienen una misma funcionalidad.
        function cargarConstante (methodName, scopeVar) {
            return UsuariosService[methodName]().then(function(result) {
                $scope[scopeVar] = angular.fromJson(result.data);
            }, null);
        }

        $scope.cargarTiposUsuarios = function() {
            // TODO: agregar funcionalidad
            $scope.tiposUsuarios = [];
        };

        var cargarRoles = function() {
            // TODO: agregar funcionalidad
            return RolesService.read()
                .then(function(result) {
                    $scope.roles = angular.fromJson(result.data);
                }, null);
        };

        var init = function() {
            UsuariosService.readById($stateParams.id).then(function(result) {
                $scope.usuario = angular.fromJson(result.data);
                $scope.usuario.FechaIngreso = $filter('date')($scope.usuario.FechaIngreso, $scope.dateFormat);
                $scope.usuario.Rol = $scope.usuario.Rol.Id;
                $scope.usuario.ResetPass = 0;
                cargarConstante('listarTiposId', 'tiposId').then(function() {
                    cargarConstante('listarNacionalidades', 'nacionalidades').then(function() {
                        cargarRoles().then(function() {
                        });
                    });
                });
            });
        };

        init();
    }

})(window.angular);